<template>
  <div class="authority">
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true">
        <el-form-item label="文件名">
          <el-input v-model="searchInfo.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker v-model="searchInfo.time" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width:400px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">
            查询
          </el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">文件上传</el-button>
      </div>
      <div class="ant-alert-info">
        <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
          <div class="pop-content">
            <div class="pop-title">自定义列</div>
            <div class="check-list">
              <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <template #reference>
            <div class="anticon">
              <el-icon size="16" color="#1890ff">
                <Setting />
              </el-icon>
              <div style="margin-left: 2px;">自定义列</div>
            </div>
          </template>
        </el-popover>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column align="left" label="文件名" prop="name" v-if="checkedColumns.includes('文件名')"></el-table-column>
        <el-table-column align="left" label="上传时间" v-if="checkedColumns.includes('上传时间')">
          <template #default="scope">
            <span>{{ formatTimestamp(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="上传人" prop="createUser"
          v-if="checkedColumns.includes('上传人')"></el-table-column>
        <el-table-column align="left" label="下载次数" prop="downloadTimes"
          v-if="checkedColumns.includes('下载次数')"></el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="80" v-if="checkedColumns.includes('操作')">
          <template #default="scope">
            <el-button type="primary" link icon="download" @click="download(scope.row)">
              下载
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog">取消</el-button>
            <!-- <el-button type="primary" @click="enterDialog">确定</el-button> -->
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
        <div class="section-title">提示</div>
        <div class="tips">
          <div>1.请上相关附件</div>
          <div>2.可上传doc,docx,xls,xlsx,pdf,jpg,bmp,png,txt格式文件(最大200M)</div>
        </div>
        <div class="section-title">上传区域</div>
        <div class="">
          <el-upload ref="uploadRef" v-model:file-list="fileList" multiple :action="adminUrl"
            :on-success="uploadSuccess" :headers="headerOdj" :auto-upload="false" :on-change="handleChange">
            <template #trigger>
              <el-button type="primary" @click="addUnit">选择多文件</el-button>
            </template>
            <el-button class="ml-3" type="success" @click="submitUpload">
              开始上传
            </el-button>
          </el-upload>
        </div>
        <el-table :data="wenjianData">
          <el-table-column prop="name" label="文件名" />
          <el-table-column align="left" label="大小" prop="size"></el-table-column>
          <el-table-column align="left" label="状态">
            <template #default="scope">
              <el-tag type="danger" v-if="scope.row.status == 'ready'">未上传</el-tag>
              <el-tag type="primary" v-else>已上传</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="left" label="操作">
            <template #default="scope">
              <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  getWjList,
  createWj,
  deleteWj
} from '@/api/xitongpeizhi'

import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { formatTimestamp } from '@/utils/format'
// 通过该函数，可以获取组件当前所在的表单项formItem
const { formItem } = useFormItem()

defineOptions({
  name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
  ico: '',
  jumpType: '',
  jumpUrl: '',
  name: '',
  type: ''
})

const searchInfo = ref({
  name: '',
  time: [],
  timeStart: '',
  timeEnd: ''
})

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
let validateImage = (rule, value, callback) => {
  if (!form.value.ico) {
    callback(new Error('请上传图片'))
  } else {
    callback()
  }
}
const rules = reactive({
  name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
  ico: [{ required: true, validator: validateImage, trigger: 'change' }],
  type: [{ required: true, message: '请选择应用类别', trigger: 'change' }],
  jumpType: [{ required: true, message: '请选择跳转类型', trigger: 'change' }]
})

const yyglForm = ref(null)

const initForm = () => {
  yyglForm.value.resetFields()
  form.value = {
    ico: '',
    jumpType: '',
    jumpUrl: '',
    name: '',
    type: ''
  }
  fileList.value = []
  wenjianData.value =[]
}
const wenjianData = ref([])
const checkedColumns = ref(['序号', '文件名', '上传时间', '上传人', '下载次数', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).wjxz) {
  checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).wjxz
}
const columns = ref(['序号', '文件名', '上传时间', '上传人', '下载次数', '操作'])
const handleColumnsChange = (val) => {
  let obj = {

  }
  if (localStorage.getItem('columnData')) {
    obj = JSON.parse(localStorage.getItem('columnData'))
  }
  obj.wjxz = val
  localStorage.setItem('columnData', JSON.stringify(obj))
}
const isEdit = ref(false)
const dialogTitle = ref('新增文件')
const addUnit = () => {
  dialogTitle.value = '新增文件'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}

const handleClose = (done) => {
  initForm()
  done()
}
const handleUserClose = (done) => {
  initUserForm()
  done()
}
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await getWjList({
    pageNumber: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value
  })
  if (res.code == 200) {
    tableData.value = res.result.data
    total.value = res.result.total
  }
}
getTableData()
const areaList = ref(['常用应用', '办事大厅'])
const typeList = ref([{ name: '内部URL', id: 1 }, { name: '外部URL', id: 2 }])
const roleList = ref([])
onMounted(() => {

})

const enterDialog = async () => {
  yyglForm.value.validate(async (valid) => {
    if (valid) {
      let res
      if (isEdit.value) {
        res = await updateApplication(form.value)
      } else {
        res = await createApplication(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}

const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteWj(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
const onSubmit = () => {
  page.value = 1
  searchInfo.value.timeStart = searchInfo.value.time[0]
  searchInfo.value.timeEnd = searchInfo.value.time[1]
  getTableData()
}
const onReset = () => {
  searchInfo.value = {
    name: '',
    time: [],
    timeStart: '',
    timeEnd: ''
  }
  getTableData()
}
const fileList = ref([])
const handleRemove = (file) => {
  fileList.value = []
  form.value.ico = ''
}
const count = ref(0)
const uploadSuccess = async (res) => {
  if (res.code != 200) {
    ElMessage({
      type: 'warning',
      message: res.message
    })
    fileList.value.pop()
    return
  }
  count.value++
  if (count.value == fileList.value.length) {
    let params = {
      files: []
    }
    params.files = fileList.value.map(item => {
      return {
        name: item.name,
        size: String(item.size),
        url: item.response.result
      }
    })
    let res = await createWj(params)
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: '上传成功!'
      })
      fileList.value = []
      wenjianData.value =[]
      getTableData()
      dialogFormVisible.value = false
    }
  }
  
  //form.value.ico = res.result
  //yyglForm.value.validateField('ico')
}
const uploadRef = ref(null)

const submitUpload = async () => {
  uploadRef.value.submit()
}

const handleChange = (uploadFile, uploadFiles) => {
  wenjianData.value.push({
    name: uploadFile.name,
    size: formatFileSize(uploadFile.size),
    status: uploadFile.status,
    url: ''
  })
}
function formatFileSize(size) {
  if (size < 1024) {
    return size + 'bytes';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + 'KB';
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + 'MB';
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
  }
}
const download = (row) => {
  window.open(row.url)
}
</script>

<style lang="scss">
.flex {
  .area {
    flex: 2;
    background-color: #fff;
    margin: 0.5rem 20px 0.5rem 0;
  }

  .unit {
    flex: 4;
  }
}

.ant-alert-info {
  display: flex;
  justify-content: end;
  align-items: center;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  padding: 5px;

  .anticon {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.btns {
  display: flex;
}

.section-title {
  font-weight: bold;
  font-size: 20px;
  line-height: 33px;
  padding: 8px 0 4px 14px;
  color: #4E7DFD;
  position: relative;
}

.section-title:before {
  content: '';
  position: absolute;
  top: 17px;
  left: 0;
  width: 6px;
  height: 14px;
  border-radius: 3px;
  background: #4E7DFD;
}

.tips {
  margin-bottom: 20px;
  color: #ff6666;
  margin-left: 10px;
}
</style>
